package handler

import (
	"common/models"
	"common/utils"
	"net/http"

	"github.com/gin-gonic/gin"
)

func AddLiuyan(c *gin.Context) {
	var addBody models.Message
	if err := c.BindJSON(&addBody); err != nil {
		res := gin.H{
			"msg":    "请输入留言内容",
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}

	//获取用户uuid
	token := c.Request.Header.Get("token")
	claims, _ := utils.ParseToken(token)

	check, err := addBody.AddMessage(claims.Uuid)
	if err != nil {
		res := gin.H{
			"msg":    err.Error(),
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}
	if !check {
		res := gin.H{
			"msg":    "留言失败",
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}
	res := gin.H{
		"msg":    "留言成功",
		"status": 0,
		"result": nil,
	}
	c.JSON(http.StatusOK, res)
}

//定义查询接收参数的结构体
type LiuyanQuery struct {
	Id       string `json:"id"`
	Page     int    `json:"page"`
	PageSize int    `json:"page_size"`
}

func ListLiuyan(c *gin.Context) {
	var body LiuyanQuery
	err := c.BindJSON(&body)
	if err != nil {
		res := gin.H{
			"msg":    err.Error(),
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}

	//分页
	var listBody models.Message
	list := listBody.ListMessage(body.Page, body.PageSize)
	res := gin.H{
		"msg":    "OK",
		"status": 0,
		"result": list,
	}
	c.JSON(http.StatusOK, res)
}

func DetailLiuyan(c *gin.Context) {
	var body LiuyanQuery
	err := c.BindJSON(&body)
	if err != nil {
		res := gin.H{
			"msg":    err.Error(),
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}
	//单条数据
	var DetailBody models.Message
	detail := DetailBody.DetailMessage(body.Id)
	if detail.Uuid == "" {
		res := gin.H{
			"msg":    "OK",
			"status": 0,
			"result": nil,
		}
		c.JSON(http.StatusOK, res)
		return
	}
	res := gin.H{
		"msg":    "OK",
		"status": 0,
		"result": detail,
	}
	c.JSON(http.StatusOK, res)
}

func DelLiuyan(c *gin.Context) {
	var body LiuyanQuery
	err := c.BindJSON(&body)
	if err != nil {
		res := gin.H{
			"msg":    err.Error(),
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}
	//获取用户uuid
	token := c.Request.Header.Get("token")
	claims, _ := utils.ParseToken(token)

	var listBody models.Message
	check, err := listBody.DelMessage(body.Id, claims.Uuid)
	if err != nil {
		res := gin.H{
			"msg":    err.Error(),
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}
	if !check {
		res := gin.H{
			"msg":    "删除失败",
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}
	res := gin.H{
		"msg":    "删除成功",
		"status": 0,
		"result": nil,
	}
	c.JSON(http.StatusOK, res)
}
